local game  = require "club.threecard.blackjack"

local resumer = game.ui.element()

resumer.store_watchers = 
{
    ingame = 
    {
        ["恢复游戏场景"] = function(self, store, state, initialize, args)
            if initialize and not state.scene then
                self:hide();
                return;
            end

            self:run(state.scene);
        end,

        ["阶段变更"] = function(self, store, state, initialize)
            if initialize then
                return;
            end

            if state.phase <= state.PHASE.PREPARE then
                self:hide();
            end
        end
    }
}

function resumer:ctor(ingame)
    self.ingame = ingame;
    self.res = "club.threecard.blackjack/ui/ingame.b:resumer"
end

local function in_playing(scene)
    local no = game.kbe.player().seat.no;
    for _, player in ipairs(scene.players) do
        if no == player.no then
            return true;
        end
    end

    return false;
end

local function prepare(self, scene)
    self:hide();
    self.ingame.bet_operator:on_bet_phase();
    for _, player in ipairs(scene.players) do
        if player.bet_amount > 0 then
            local seat = self.ingame.seats[player.no];
            local bet_chip = self.ingame.seats.bet_chip;
            seat:bet(bet_chip, player.bet_amount);
        end
    end
end

function resumer:run(scene)
    game.gamelib.log.debug("game scene refresh")
    self.ingame:clear_scene()

    local PHASE = game.store.ingame.state.PHASE;
    local phase_id = scene.phase_id;
    local current_no = scene.current_no;

    if phase_id <= PHASE.PREPARE then
        prepare(self, scene);
        return;
    end

    self.ingame.bet_operator:on_game_phase();

    if in_playing(scene) then
        self:hide();
    else
        self:show();
    end

    self.ingame.banker:resume(scene.banker_cards);
    for _, player in ipairs(scene.players) do
        local seat = self.ingame.seats[player.no];
        seat:resume(self.ingame.seats, player, scene);
    end

    if game.kbe.player().seat.no == scene.current_no then
        self.ingame.actions:on_actions(scene.action_ids);
    else
        self.ingame.actions:on_actions({});
    end
end

return resumer